import { app, ipcMain, IpcMainInvokeEvent, IpcMainEvent } from "electron"
import { useMain } from "../hooks/useMain"
import { ElectronDownload } from '@xmov/electron-extension'
import path from "path"
import fs from 'fs'

const windowApi = () => {
  const win: any = useMain()

  ipcMain.on('show-process', () => {
    win?.webContents.send('show-process', process.env)
  })

  // 重启应用
  ipcMain.on("relaunch", () => {
    app.relaunch()
    app.quit()
  })

  ipcMain.on('window_close', () => {
    if (!win) {
      return
    }
    win.close()
  })

  ipcMain.on('window_mini', () => {
    if (!win) {
      return
    }
    win.minimize()
  })

  ipcMain.on('window_full', () => {
    if (!win) {
      return
    }
    win.setFullScreen(true)
  })

  ipcMain.on('window_normal', () => {
    if (!win) {
      return
    }
    win.setFullScreen(false)
    win.center()
  })

  const downloadPath = app.isPackaged ? path.resolve(app.getPath('videos')) : path.resolve(app.getPath('exe'), '../', 'download')

  ipcMain.handle('window_check_download', (e: IpcMainInvokeEvent, data: string[]) => {
    return data.filter((item: string) => {
      const fileName = item.split('/').pop() || ''
      const filePath = path.resolve(downloadPath, fileName)
      return fileName && !fs.existsSync(filePath)
    })
  })

  ipcMain.handle('window_get_download', (e: IpcMainInvokeEvent, data: string[]) => {
    const cacheMap: any = {}
    for (let i = 0; i < data.length; i++) {
      const item = data[i]
      const fileName = item.split('/').pop() || ''
      const filePath = path.resolve(downloadPath, fileName)
      cacheMap[item] = 'xmov://' + filePath
    }
    return cacheMap
  })

  const electronDownload = new ElectronDownload(win)

  ipcMain.on('window_download_start', (e: IpcMainEvent, url: string) => {
    if (!win || !electronDownload) {
      return
    }
    electronDownload.download(url, downloadPath).finally(() => {
      if (win) {
        win.webContents.send('window_download_end')
      }
    })
    electronDownload.onProgress = (item: any) => {
      if (win) {
        win.webContents.send('window_download_progress', item.progress)
      }
    }
  })
}

export default windowApi
